/*******************************************************************************
 * Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

package hydrograph.ui.expression.editor.util;

import hydrograph.ui.datastructure.property.FixedWidthGridRow;
import hydrograph.ui.datastructure.property.GridRow;
import hydrograph.ui.expression.editor.Constants;
import hydrograph.ui.expression.editor.enums.DataTypes;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class FieldDataTypeMap {

	public static final FieldDataTypeMap INSTANCE=new FieldDataTypeMap();
	
	private FieldDataTypeMap() {}
	
	/**
	 * @param selectedInputFields
	 * @param outputSchema
	 * @return
	 */
	public Map<String, Class<?>> createFieldDataTypeMap(List<String> selectedInputFields,
			List<FixedWidthGridRow> outputSchema) {
		Map<String, Class<?>> fieldMap = new LinkedHashMap<String, Class<?>>();
		if(selectedInputFields!=null){
			for(String fieldName:selectedInputFields){
				fieldMap.put(fieldName, getFieldDataType(fieldName, outputSchema));
			}
		}else if(outputSchema!=null){
			for(GridRow gridRow:outputSchema){
				fieldMap.put(gridRow.getFieldName(), getFieldDataType(gridRow.getFieldName(), outputSchema));
			}
		}
		return fieldMap;
	}

	private Class<?> getFieldDataType(String field, List<FixedWidthGridRow> outputSchema) {
		Class<?> clazz = String.class;
		if (outputSchema != null) {
			for (GridRow gridRow : outputSchema) {
				if (StringUtils.equalsIgnoreCase(gridRow.getFieldName(), field)) {
					clazz = DataTypes.getDataTypeClassfromString(ExpressionEditorUtil.INSTANCE.lastString(
							gridRow.getDataTypeValue(), Constants.DOT));
				}
			}
		}
		return clazz;
	}
}
